/**
 * BanBu_PhotoShowViewController
 * @description 本文件提供单个相册展示界面
 * @package
 * @author 		yinlinlin
 * @copyright
 * @version 		1.0
 * @description 本文件提供单个相册展示界面
 */

#import "BanBu_PhotoShowViewController.h"
#import "CustomStatueBar.h"
#import "BanBu_SelectPhotosViewController.h"
#import "BanBu_PhotoAlbumSetViewController.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "AppDataManager.h"
#import "BanBu_PhotoShowCell.h"
#import "BanBu_PhotoMoveListViewController.h"
#import "BanBu_PhotoMoveListViewController.h"
#import "MWPhoto.h"
#import "PhotoandVideoViewController.h"
#import "BanBu_MWNavigationController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import "SDNCreateAlbumsViewController.h"
#import "BanBu_PhotoAlbumViewController.h"
@interface BanBu_PhotoShowViewController ()

@end

@implementation BanBu_PhotoShowViewController
@synthesize albumModel = _albumModel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.refreshDataCallBack = nil;
    self.changeAlbumCallBack = nil;
    self.deleteAlbumCallBack = nil;
    self.setCoverCallBack = nil;
    [_albumModel release];
    _albumModel = nil;
    [networkMediaObjects release];
    networkMediaObjects = nil;
    [broswerPhotos release];
    broswerPhotos = nil;
    [_photoList release];
    _photoList = nil;
    [_phototableV release];
    _phototableV = nil;
    [_managePhotoArr release];
    _managePhotoArr = nil;
    //    [_cover_url release];
    //    _cover_url = nil;
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    [super viewWillDisappear:animated];
}

//上传照片成功的通知
- (void)mangerUpdateBackDataWithNSNotification:(NSNotification*)notification
{
    if (_progressQueue.updateArr.count == 0)
    {
        [_queueBu setHidden:YES];
    }
    else
    {
        [_queueBu setHidden:NO];
        _queueNumLa.text = [NSString stringWithFormat:@"%d",_progressQueue.updateArr.count];
    }
    
    NSLog(@"%@",[notification object]);
    NSDictionary * updateDict = [notification object];
    if ([[updateDict valueForKey:@"album_id"] isEqualToString:_albumModel.album_id])
    {
        [self mangerUpdateBackData:[notification object]];
    }
    
}
- (void)removeNilImageV
{
    [_nilImageV removeGestureRecognizer:[_nilImageV.gestureRecognizers objectAtIndex:0]];
    
    
    [_nilImageV removeFromSuperview];
    _nilImageV = nil;
    [_menu setHidden:NO];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    _isEditing = NO;
    _page = 1;
    //获取相册照片列表,请求第一页（48张）的数据
    [self getPhotosOfAlbumWithPage:_page];
    self.view.backgroundColor = self.view.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    [self initManageView];
    // Do any additional setup after loading the view.
    _photoList = [[NSMutableArray alloc]init];
    _managePhotoArr  = [[NSMutableArray alloc]init];
    networkMediaObjects = [[NSMutableArray alloc]init];
    broswerPhotos = [[NSMutableArray alloc]init];
    _phototableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height - 44) style:UITableViewStylePlain];
    _phototableV.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    _phototableV.delegate = self;
    _phototableV.dataSource = self;
    _phototableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_phototableV];
    //自定义navigationItem.titleView
    UIView * titleView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 240, 44)]autorelease];
    titleView.backgroundColor = [UIColor clearColor];
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 160, 44)];
    titleLabel.text = _albumModel.album_title;
    titleLabel.textAlignment = kTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.tag = 1001;
    [titleView addSubview:titleLabel];
    [titleLabel release];
    self.navigationItem.titleView = titleView;
    
    if ([_albumModel.user_id isEqualToString:MyAppDataManager.useruid])
    {
        //添加空相册引导页
        CGRect  rect = CGRectMake(0, __MainScreen_Height + 20 - 568, 320, 568);
        _nilImageV = [[UIImageView alloc]initWithFrame:rect];
        _nilImageV.image = [UIImage imageNamed:@"album_nilImage.png"];
        [self.navigationController.view addSubview:_nilImageV];
        [_nilImageV release];
        [_nilImageV setHidden:YES];
        [_nilImageV setUserInteractionEnabled:YES];
        
        UITapGestureRecognizer * singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeNilImageV)];
        [_nilImageV addGestureRecognizer:singleTap];
        [singleTap release];
        UILabel * nilLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(43, 440, 280, 15)];
        nilLabel2.text = NSLocalizedString(@"nilAlbumNotice2", nil);
        [_nilImageV addSubview:nilLabel2];
        nilLabel2.textColor = [UIColor whiteColor];
        nilLabel2.backgroundColor = [UIColor clearColor];
        nilLabel2.font = [UIFont systemFontOfSize:16.0];
        [nilLabel2 release];
        //添加上传本地半圆视频的观察者
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendLocalVideo:) name:kSendLocalVideoNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mangerUpdateBackDataWithNSNotification:) name:kSendPhotosSuccessNotification object:nil];
        //查看上传队列的按钮
        _queueBu = [UIButton  buttonWithType:UIButtonTypeCustom];
        _queueBu.frame = CGRectMake(189, 10, 47, 24);
        [_queueBu setImageEdgeInsets:UIEdgeInsetsMake(1.5, 13, 1.5, 13)];
        [_queueBu setImage:[UIImage imageNamed:@"album_queue.png"] forState:UIControlStateNormal];
        [_queueBu addTarget:self action:@selector(pushToUpdateQueue) forControlEvents:UIControlEventTouchDown];
        [_queueBu setHidden:YES];
        [self.navigationItem.titleView addSubview:_queueBu];
        //显示上传队列数量的圆点背景
        UIImageView * queueNumImg = [[UIImageView alloc]initWithFrame:CGRectMake(30, 0, 16, 16)];
        queueNumImg.image = [UIImage imageNamed:@"album_queueNoBack.png"];
        [_queueBu addSubview:queueNumImg];
        [queueNumImg release];
        //显示正在上传的数量
        _queueNumLa = [[UILabel alloc]initWithFrame:CGRectMake(30, 3, 16, 10)];
        _queueNumLa.font = [UIFont boldSystemFontOfSize:12.0];
        _queueNumLa.textAlignment = NSTextAlignmentCenter;
        _queueNumLa.backgroundColor = [UIColor clearColor];
        _queueNumLa.textColor = [UIColor whiteColor];
        [_queueBu addSubview:_queueNumLa];
        [_queueNumLa release];
        _progressQueue = [BanBu_ProgressController sharedManager];
        if (_progressQueue.updateArr.count > 0)
        {
            _queueNumLa.text = [NSString stringWithFormat:@"%d",_progressQueue.updateArr.count];
            [_queueBu setHidden:NO];
        }
        //使用回调容易产生内存泄露，所以改用通知
        __block UIButton * bqueueBu = _queueBu;
        __block UILabel * bqueueNumLa = _queueNumLa;
        [_progressQueue setUpdateNumChangeCallBack:^(int num)
         {
             if (!bqueueBu)
             {
                 return;
             }
             NSLog(@"bqueueBu:::%@",bqueueBu);
             if (num == 0)
             {
                 [bqueueBu setHidden:YES];
             }
             else
             {
                 [bqueueBu setImage:[UIImage imageNamed:@"album_queue.png"] forState:UIControlStateNormal];
                 [bqueueBu setHidden:NO];
                 bqueueNumLa.text = [NSString stringWithFormat:@"%d",num];
             }
         }];
        
        //获取按钮title的宽度
        CGFloat btnLen = [NSLocalizedString(@"cancelNotice", nil) sizeWithFont:[UIFont systemFontOfSize:16.0] constrainedToSize:CGSizeMake(80, 24)].width;
        
        _quitBu = [UIButton  buttonWithType:UIButtonTypeCustom];
        _quitBu.frame = CGRectMake(240 - btnLen - 10, 10, btnLen + 20, 24);
        _quitBu.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [_quitBu setTitle:NSLocalizedString(@"cancelNotice", nil) forState:UIControlStateNormal];
        [_quitBu addTarget:self action:@selector(quitEditState) forControlEvents:UIControlEventTouchDown];
        [_quitBu setHidden:YES];
        [self.navigationItem.titleView addSubview:_quitBu];
        
        //**********************QuadCurveMenu******************
        // Camera MenuItem.拍照上传按钮
        QuadCurveMenuItem *cameraMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_camera.png"] withIntro:NSLocalizedString(@"album_cameraPhoto", nil)];
        // Photo MenuItem.上传本地图片按钮
        QuadCurveMenuItem *photoMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_photo.png"] withIntro:NSLocalizedString(@"album_localPhoto", nil)];
        
        // pickup MenuItem.拍摄视频按钮
        // video MenuItem.上传本地视频按钮
        QuadCurveMenuItem *videoMenuItem;
        QuadCurveMenuItem *pickupMenuItem;
        
//        //头像相册不能上传视频
//        if ([_albumModel.album_id isEqualToString:Album_face])
//        {
//            videoMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_video_an.png"] withIntro:NSLocalizedString(@"album_localVideo", nil)];
//            videoMenuItem.userInteractionEnabled = NO;
//            
//            pickupMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_pickup_an.png"] withIntro:NSLocalizedString(@"album_cameraVideo", nil)];
//            pickupMenuItem.userInteractionEnabled = NO;
//        }
//        else
//        {
//            videoMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_video.png"] withIntro:NSLocalizedString(@"album_localVideo", nil)];
//            pickupMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_pickup.png"] withIntro:NSLocalizedString(@"album_cameraVideo", nil)];
//        }
        videoMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_video.png"] withIntro:NSLocalizedString(@"album_localVideo", nil)];
        pickupMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_pickup.png"] withIntro:NSLocalizedString(@"album_cameraVideo", nil)];
        // setting MenuItem.相册属性按钮
        QuadCurveMenuItem *settingMenuItem;
        //系统相册不可以更改属性
        if (_albumModel.album_type == ALBUM_SYSTEM)
        {
            settingMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_setting_an.png"] withIntro:NSLocalizedString(@"album_albumProper", nil)];
            settingMenuItem.userInteractionEnabled = NO;
        }
        else
        {
            settingMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_setting.png"] withIntro:NSLocalizedString(@"album_albumProper", nil)];
        }
        
        // manger MenuItem.管理相册
        QuadCurveMenuItem *mangerMenuItem;
        mangerMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_manger.png"] withIntro:NSLocalizedString(@"album_mangerAlbum", nil)];
        
        // delete MenuItem.删除相册
        QuadCurveMenuItem *deleteMenuItem;
        //系统相册不可删除
        if (_albumModel.album_type == ALBUM_SYSTEM)
        {
            deleteMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_delete_an.png"] withIntro:NSLocalizedString(@"album_deleteAlbum", 删除相册)];
            deleteMenuItem.userInteractionEnabled = NO;
        }
        else
        {
            deleteMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"album_delete.png"] withIntro:NSLocalizedString(@"album_deleteAlbum", 删除相册)];
        }
        //更多按钮
//        QuadCurveMenuItem * moreMenuItem = [[QuadCurveMenuItem alloc]initWithCustomImage:[UIImage imageNamed:@"album_more.png"] withIntro:NSLocalizedString(@"addBtn", nil)];
        
        NSArray *menus = [NSArray arrayWithObjects:cameraMenuItem, photoMenuItem, pickupMenuItem, videoMenuItem, settingMenuItem, mangerMenuItem, deleteMenuItem, nil];
        [cameraMenuItem release];
        [photoMenuItem release];
        [pickupMenuItem release];
        [videoMenuItem release];
        [settingMenuItem release];
        [mangerMenuItem release];
        [deleteMenuItem release];
//        [moreMenuItem release];
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height - 44) menus:menus withShare:NO];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
        [_menu setHidden:YES];
        [_menu release];
    }
    
    
    moreView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease];
    //    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    //    lab.font= [UIFont systemFontOfSize:15];
    //    lab.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:250.0/255.0 blue:239.0/255.0 alpha:1];
    //    lab.textAlignment = kTextAlignmentCenter;
    //    lab.textColor = [UIColor grayColor];
    //    lab.backgroundColor = [UIColor clearColor];
    //    [moreView addSubview:lab];
    //    [lab release];
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:loadingView];
    [loadingView release];
    
    _moreBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_moreBu setTitle:NSLocalizedString(@"loadMoreButton", nil) forState:UIControlStateNormal];
    _moreBu.frame = CGRectMake((_phototableV.frame.size.width - 248) / 2.0, 10, 248, 20);
    [_moreBu addTarget:self action:@selector(photosClickMore) forControlEvents:UIControlEventTouchUpInside];
    
    _moreBu.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_moreBu setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [moreView addSubview:_moreBu];
    _phototableV.tableFooterView = moreView;
    
    
}

- (void)sendLocalVideo:(NSNotification *)notifi
{
    NSString * videoPath = [[notifi object]valueForKey:@"video"];
    //    MsgData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.mp4",videoName]];
    //    thumbnailData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
    BanBu_SelectPhotosViewController * selectPhoto= [[BanBu_SelectPhotosViewController alloc]init];
//    selectPhoto.title = NSLocalizedString(@"album_update", 上传视频);
    selectPhoto.file_type = FILE_KOOLALBUM;
    
    NSDictionary * info = [NSDictionary dictionaryWithObjectsAndKeys:videoPath,@"videoPath", nil];
    selectPhoto.info = info;
    selectPhoto.albumModel = _albumModel;
    __block id bself = self;
    [selectPhoto setUpdateSuccessCallBack:^(NSDictionary *updateDict)
     {
         if (!bself)
         {
             return;
         }
         [bself mangerUpdateBackData:updateDict];
     }];
    [self.navigationController pushViewController:selectPhoto animated:YES];
    [selectPhoto release];
    
    
}
#pragma mark - QuadCurveMenuDelegate
- (void)quadCurveMenu:(QuadCurveMenu *)menu didSelectIndex:(NSInteger)idx
{
    NSLog(@"Select the index : %d",idx);
    //拍照上传
    if (idx == 0)
    {
        //判断设备是否支持拍照
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //设置setAllowsEditing为YES，否则下个界面可能取不出要上传的照片
        [picker setAllowsEditing:YES];
        [self presentViewController:picker animated:YES completion:nil];
        [picker release];
        //设置ios7下状态栏显示文字的背景色为黑色
        if (IS_IOS_7)
        {
            NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"black",@"color", nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:kThemeDidChangeAndIOS7Notification object:dic];
        }
        return;
    }
    //本地照片上传
    if (idx == 1)
    {
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        picker.navigationBar.translucent = NO ;
        picker.maximumNumberOfSelection = 9;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:NULL];
        [picker release];
        picker = nil;
        return;
    }
    //拍摄视频
    if (idx == 2)
    {//判断设备是否支持拍照
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            return;
        }
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        //sourcetype有三种分别是camera，photoLibrary和photoAlbum
        NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        //Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
        ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
        //设置媒体类型为public.movie
        
        ipc.videoMaximumDuration = 5.0f;//5秒
        ipc.delegate = self;//设置委托
        [self presentViewController:ipc animated:YES completion:nil];
        [ipc release];
        return;
    }
    //上传本地视频
    if (idx == 3)
    {
        BanBu_PhotoAlbumViewController * photo = [[BanBu_PhotoAlbumViewController alloc]init];
        //半圆本地相册
        photo.type_file = FILE_KOOLALBUM;
        [self.navigationController pushViewController:photo animated:YES];
        [photo release];
        
        //        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        //        imagePicker.delegate = self;
        //        imagePicker.allowsEditing = YES;
        //        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //        imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
        //        [self presentModalViewController:imagePicker animated:YES];
        //        [imagePicker release];
        //        return;
    }
    //修改相册属性
    if (idx == 4)
    {
        SDNCreateAlbumsViewController *nestedNav = [[SDNCreateAlbumsViewController alloc] init];
        nestedNav.album_model = _albumModel;
        __block BanBu_AlbumModel * balbum_model = _albumModel;
        __block BanBu_PhotoShowViewController * bself = self;
        [nestedNav setChangeSuccessCallBack:^(BanBu_AlbumModel *change_model)
         {
             //修改相册属性（名称）
             UILabel * titleLa = (UILabel *)[bself.navigationItem.titleView viewWithTag:1001];
             titleLa.text = change_model.album_title;
             balbum_model.album_title = change_model.album_title;
             balbum_model.personalbum_type = change_model.personalbum_type;
             balbum_model.opengroup = change_model.opengroup;
             balbum_model.hidegroup = change_model.hidegroup;
             balbum_model.question = change_model.question;
             balbum_model.answer = change_model.answer;
             if (_changeAlbumCallBack)
             {
                 _changeAlbumCallBack(balbum_model);
             }
         }];
        [self.navigationController pushViewController:nestedNav animated:YES];
        [nestedNav release];
        return;
    }
    //管理相册
    if (idx == 5)
    {
        _isEditing = YES;
        [_quitBu setHidden:NO];
        [_queueBu setHidden:YES];
        [UIView animateWithDuration:0.3 animations:^{
            [_phototableV setFrame:CGRectMake(_phototableV.frame.origin.x, _phototableV.frame.origin.y, __MainScreen_Width, _phototableV.frame.size.height - 51.5)];
            [_manageView setFrame:CGRectMake(0, _phototableV.frame.size.height, __MainScreen_Width, 51.5)];
        }];
        [_menu setHidden:YES];
        return;
    }
    //删除相册
    if (idx == 6)
    {
        if ((_albumModel.numCount == 0) && (_photoList.count == 0))
        {
            //删除相册
            NSLog(@"删除相册");
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
            NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",nil];
            NSLog(@"要删除的相册的相关信息:%@",parDic);
            [AppComManager getBanBuData:BanBu_v2_Delete_Album par:parDic delegate:self];
            return;
        }
        NSString * message = [NSString stringWithFormat:@"%@ %d %@",NSLocalizedString(@"album_delete_message1", 相册删除1),_albumModel.numCount,NSLocalizedString(@"album_delete_message2", 相册删除2)];
        //        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"album_delete_title", 相册删除提示) message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"album_delete_title", 相册删除提示) message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil), nil];
        alert.tag = ALERT_DELETEALBUM;
        [alert show];
        [alert release];
        return;
    }
}

#pragma mark - 查看上传队列
- (void)pushToUpdateQueue
{
    
    [self.navigationController pushViewController:_progressQueue animated:YES];
    
}
#pragma mark - 退出编辑状态

- (void)quitEditState
{
    _isEditing = NO;
    [_quitBu setHidden:YES];
    if (_progressQueue.updateArr.count > 0)
    {
        _queueNumLa.text = [NSString stringWithFormat:@"%d",_progressQueue.updateArr.count];
        [_queueBu setHidden:NO];
    }
    
    [UIView animateWithDuration:0.3f animations:^{
        [_phototableV setFrame:CGRectMake(_phototableV.frame.origin.x, _phototableV.frame.origin.y, __MainScreen_Width, _phototableV.frame.size.height + 51.5)];
        [_manageView setFrame:CGRectMake(0, _phototableV.frame.size.height, __MainScreen_Width, 51.5)];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            [_menu setHidden:NO];
            
        }];
        
    }];
    
    _photoMoveBu.userInteractionEnabled = NO;
    [_photoMoveBu setSelected:NO];
    
    _setHeadBu.userInteractionEnabled = NO;
    [_setHeadBu setSelected:NO];
    
    _setCoverBu.userInteractionEnabled = NO;
    [_setCoverBu setSelected:NO];
    [_phototableV reloadData];
    
}

#pragma mark - 获取相册列表

- (void)getPhotosOfAlbumWithPage:(NSInteger)page
{
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",[NSString stringWithFormat:@"%d",page],@"pageno",_albumModel.user_id,@"userid", nil];
    NSLog(@"%@",parDic);
    [AppComManager getBanBuAlbumData:BanBu_v2_Get_Listof_Albumid par:parDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
}


#pragma mark - 接口返回数据
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1];
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Get_Listof_Albumid])
    {
        NSLog(@"获取相册中照片列表数据:%@",resDic);
        //加载完成
        _isLoading = NO;
        [loadingView stopAnimating];
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            if (_page == 1)
            {
                [_photoList removeAllObjects];
                [broswerPhotos removeAllObjects];
                [networkMediaObjects removeAllObjects];
            }
            _page ++;
            __block NSMutableArray *picArr = [[NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]] retain];
            if(!picArr.count)
            {
                //没有数据了，取消加载更多
                _hasMore = NO;
                if (_photoList.count == 0)
                {
                    [_moreBu setHidden:YES];
                }
                else
                {
                    [_moreBu setHidden:NO];
                    [_moreBu setTitle:NSLocalizedString(@"album_nomorePhotos", nil) forState:UIControlStateNormal];
                }
                
                
                [picArr release];
                [_phototableV reloadData];
            }
            else
            {
                
                for (NSDictionary * photoDateDict in picArr)
                {
                    NSLog(@"%@",photoDateDict);
                    NSMutableArray * dateModelArr = [[NSMutableArray alloc]init];
                    
                    NSArray * dateArr = [photoDateDict objectForKey:@"photolist"];
                    
                    for (NSDictionary * mediaDict in dateArr)
                    {
                        BanBu_MediaModel * mediaModel = [[BanBu_MediaModel alloc]init];
                        mediaModel.photo_id = [mediaDict objectForKey:@"photoid"];
                        mediaModel.albumModel = _albumModel;
                        mediaModel.media_type = [mediaDict objectForKey:@"kindof"];
                        
                        NSDictionary * medialist = [mediaDict objectForKey:@"medialist"];
                        //已经审核
                        if ([[medialist valueForKey:@"pass"] boolValue])
                        {
                            mediaModel.audit = YES;
                        }
                        else
                        {
                            mediaModel.audit = NO;
                        }
                        mediaModel.thumb_url = [medialist valueForKey:@"thumb"];
                        mediaModel.full_url = [medialist valueForKey:@"full"];
                        if ([medialist valueForKey:@"soundlen"])
                        {
                            mediaModel.soundlen = [medialist valueForKey:@"soundlen"];
                        }
                        else
                        {
                            mediaModel.soundlen = @"6";
                        }
                        NSString * caption = [[NSString alloc]initWithData:[NSData dataFromBase64String:[medialist valueForKey:@"text"]] encoding:NSUTF8StringEncoding];
                        mediaModel.intro_text = caption;
                        [caption release];
                        //有语音描述
                        if (![[medialist valueForKey:@"sound"] isEqualToString:@""])
                        {
                            mediaModel.intro_soundurl = [medialist valueForKey:@"sound"]
                            ;
                        }
                        else
                        {
                            mediaModel.intro_soundurl = nil;
                        }
                        MWPhoto *photo;
                        if ([mediaModel.media_type isEqualToString:@"v"])
                        {
                            photo = [MWPhoto photoWithURL:[NSURL URLWithString:mediaModel.thumb_url] withCaption:mediaModel.intro_text];
                        }
                        else
                        {
                            photo = [MWPhoto photoWithURL:[NSURL URLWithString:mediaModel.full_url] withCaption:mediaModel.intro_text];
                        }
                        [broswerPhotos addObject:photo];
                        
                        [networkMediaObjects addObject:mediaModel];
                        [dateModelArr addObject:mediaModel];
                        [mediaModel release];
                    }
                    if (dateModelArr.count > 0)
                    {
                        NSMutableDictionary * lastdateDic = [_photoList lastObject];
                        //这次返回的第一组数据日期等于上次返回最后一组的日期，返回的数据加到最后一个相册里面
                        if ([[lastdateDic valueForKey:@"date"] isEqualToString:[photoDateDict objectForKey:@"dateof"]])
                        {
                            NSMutableArray * lastMoreArr = [[NSMutableArray alloc]initWithArray:[lastdateDic valueForKey:@"photolist"]];
                            [lastMoreArr addObjectsFromArray:dateModelArr];
                            //组成新的数组
                            NSMutableDictionary * lastMoreDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[photoDateDict objectForKey:@"dateof"],@"date",lastMoreArr,@"photolist", nil];
                            [lastMoreArr release];
                            [dateModelArr release];
                            [_photoList removeLastObject];
                            [_photoList addObject:lastMoreDic];
                            [lastMoreDic release];
                            
                        }
                        else
                        {
                            NSMutableDictionary * dateDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[photoDateDict objectForKey:@"dateof"],@"date",dateModelArr,@"photolist", nil];
                            [dateModelArr release];
                            [_photoList addObject:dateDict];
                            [dateDict release];
                        }
                        
                    }
                    else
                    {
                        [dateModelArr release];
                    }
                    
                }
                if (networkMediaObjects.count < 20)
                {
                    [_moreBu setHidden:YES];
                    _hasMore = NO;
                }
                else
                {
                    [_moreBu setHidden:NO];
                    [_moreBu setTitle:NSLocalizedString(@"loadMoreButton", nil) forState:UIControlStateNormal];
                    _hasMore = YES;
                }
                [picArr release];
                [_phototableV reloadData];
                
            }
        }
        if (networkMediaObjects.count == 0)
        {
            if (_nilImageV)
            {
                [_nilImageV setHidden:NO];
                [_menu setHidden:YES];
            }
            
            else
            {
                [_menu setHidden:NO];
            }
        }
        else
        {
            
            if (_nilImageV)
            {
                [self removeNilImageV];
                [_menu setHidden:NO];
            }
            
        }
    }
    else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Move_Fileof_Albumid])
    {
        NSLog(@"转移或的复制相册中照片返回数据:%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            if (_selectTag == ACTION_COPY)
            {
                NSLog(@"复制照片成功");
            }
            else if(_selectTag == ACTION_MOVE)
            {
                NSLog(@"转移照片成功");
            }
            [self quitEditState];
            //重新获取数据
            _page = 1;
            if (_refreshDataCallBack)
            {
                _refreshDataCallBack();
            }
            [self getPhotosOfAlbumWithPage:_page];
            return;
        }
    }
    else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Set_AlbumFace])
    {
        NSLog(@"设置封面照片返回数据:%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            [_phototableV reloadData];
            NSLog(@"设置封面成功");
            if (_setCoverCallBack)
            {
                _setCoverCallBack([resDic valueForKey:@"faceurl"]);
            }
            [_phototableV reloadData];
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Set_UserFace])
    {
        NSLog(@"设置头像返回数据:%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSLog(@"设置头像成功");
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifySucceed", nil) activityAnimated:NO duration:1];
            NSMutableDictionary *infoUpdata = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
            BanBu_MediaModel * setfaceModel = [_managePhotoArr objectAtIndex:0];
            [infoUpdata setValue:setfaceModel.thumb_url forKey:@"uface"];
            [UserDefaults setValue:infoUpdata forKey:MyAppDataManager.useruid];
            [UserDefaults synchronize];
            [self quitEditState];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifyFail", nil) activityAnimated:NO duration:1];
        }
    }
    
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Delete_Album])
    {
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifySucceed", nil) activityAnimated:NO duration:1];
            NSLog(@"删除相册成功");
            if (_deleteAlbumCallBack)
            {
                _deleteAlbumCallBack();
            }
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifyFail", nil) activityAnimated:NO duration:1];
        }
        
    }
    else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Post_Albumfile_Byuser])
    {
        [self mangerUpdateBackData:resDic];
    }
    [_managePhotoArr removeAllObjects];
}

#pragma mark - 点击右上角设定按钮
- (void)setBuPressed
{
    BanBu_PhotoAlbumSetViewController * albumSet = [[BanBu_PhotoAlbumSetViewController alloc]init];
    [self.navigationController pushViewController:albumSet animated:YES];
    [albumSet release];
    albumSet = nil;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"info:%@",info);
    __block id bself = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        BanBu_SelectPhotosViewController * selectPhoto= [[BanBu_SelectPhotosViewController alloc]init];
        selectPhoto.file_type = FILE_PICKER;
        selectPhoto.info = info;
        selectPhoto.albumModel = _albumModel;
        
        [selectPhoto setUpdateSuccessCallBack:^(NSDictionary *updateDict)
         {
             if (!bself)
             {
                 return;
             }
             [bself mangerUpdateBackData:updateDict];
         }];
        [self.navigationController pushViewController:selectPhoto animated:YES];
        [selectPhoto release];
    }];
}


#pragma mark - Assets Picker Delegate

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    __block BanBu_PhotoShowViewController* bself = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if (assets.count == 0)
        {
            return ;
        }
        BanBu_SelectPhotosViewController * selectPhoto= [[BanBu_SelectPhotosViewController alloc]init];
//        selectPhoto.title = NSLocalizedString(@"album_update", 上传照片);
        selectPhoto.photosArr = assets;
        selectPhoto.albumModel = _albumModel;
        selectPhoto.file_type = FILE_ALASSET;
        [selectPhoto setUpdateSuccessCallBack:^(NSDictionary *updateDict)
         {
             if (!self)
             {
                 return ;
             }
             [bself mangerUpdateBackData:updateDict];
         }];
        [bself.navigationController pushViewController:selectPhoto animated:YES];
        [selectPhoto release];
        
    }];
}
#pragma mark - 上传完成之后的数据处理
/**
 * @函数名称：mangerUpdateBackData
 * @函数描述：处理上传照片返回的数据，加入到原有的数据源
 * @输入参数：(NSDictionary *)updateDict，返回的字典
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)mangerUpdateBackData:(NSDictionary *)updateDict
{
    if (!self)
    {
        return;
    }
    if (!updateDict || (updateDict == nil) ||(updateDict == NULL))
    {
        NSLog(@"上传失败");
        return;
    }
    if ([updateDict allValues].count <= 3)
    {
        return;
    }
    __block NSMutableArray * bphotolist = _photoList;
    __block NSMutableArray * bnetworkArr = networkMediaObjects;
    __block NSMutableArray * bbroswerPhotos = broswerPhotos;
    
    __block UITableView * bphotoTableV = _phototableV;
    
    BanBu_MediaModel * mediaModel = [[BanBu_MediaModel alloc]init];
    mediaModel.media_type = [updateDict valueForKey:@"kindof"];
    mediaModel.photo_id = [updateDict valueForKey:@"photoid"];
    mediaModel.thumb_url = [updateDict valueForKey:@"fileurl"];
    mediaModel.full_url = [updateDict valueForKey:@"fullurl"];
    mediaModel.audit = NO;
    if ([updateDict valueForKey:@"soundlen"])
    {
        mediaModel.soundlen = [updateDict valueForKey:@"soundlen"];
    }
    else
    {
        mediaModel.soundlen = @"6";
    }
    mediaModel.intro_text = [updateDict valueForKey:@"text"];
    //判断上传照片是否含有语音描述
    if ([[updateDict valueForKey:@"soundurl"] hasSuffix:@".amr"])
    {
        mediaModel.intro_soundurl = [updateDict valueForKey:@"soundurl"];
    }
    else
    {
        mediaModel.intro_soundurl = nil;
    }
    _albumModel.numCount ++;
    //添加照片，相册列表中相册数量改变
    if (_refreshDataCallBack)
    {
        _refreshDataCallBack();
    }
    if (_nilImageV)
    {
        [self removeNilImageV];
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr = [formatter stringFromDate:[NSDate date]];
    //之前存在照片，不是第一次上传
    if (bphotolist.count > 0)
    {
        NSDictionary * lastDateDict = [bphotolist objectAtIndex:0];
        
        //如果相册中有当天上传的照片，将照片存到当天数组中
        if ([[lastDateDict valueForKey:@"date"] isEqualToString:dateStr])
        {
            NSMutableDictionary * blastDict = [[NSMutableDictionary alloc]initWithDictionary:lastDateDict];
            NSMutableArray * photolist = [blastDict valueForKey:@"photolist"];
            [photolist insertObject:mediaModel atIndex:0];
            [bphotolist removeObjectAtIndex:0];
            [bphotolist insertObject:blastDict atIndex:0];
            [blastDict release];
            if (!bphotoTableV)
            {
                return;
            }
            [bphotoTableV reloadData];
        }
        //如果相册中没有当天上传的照片，另外创建当天数组
        else
        {
            NSMutableArray * todayArr = [[NSMutableArray alloc]initWithObjects:mediaModel, nil];
            NSDictionary * todayDict = [[NSDictionary alloc]initWithObjectsAndKeys:dateStr,@"date",todayArr,@"photolist", nil];
            [bphotolist insertObject:todayDict atIndex:0];
            [bphotoTableV reloadData];
        }
    }
    //第一次上传照片，之前不存在相册的照片
    else
    {
        NSMutableArray * todayArr = [[NSMutableArray alloc]initWithObjects:mediaModel, nil];
        NSDictionary * todayDict = [[NSDictionary alloc]initWithObjectsAndKeys:dateStr,@"date",todayArr,@"photolist", nil];
        [bphotolist insertObject:todayDict atIndex:0];
        [bphotoTableV reloadData];
    }
    [bnetworkArr insertObject:mediaModel atIndex:0];
    MWPhoto * photo;
    if ([mediaModel.media_type isEqualToString:@"v"])
    {
        photo = [MWPhoto photoWithURL:[NSURL URLWithString:mediaModel.thumb_url] withCaption:mediaModel.intro_text];
    }
    else
    {
        photo = [MWPhoto photoWithURL:[NSURL URLWithString:mediaModel.full_url] withCaption:mediaModel.intro_text];
    }
    
    [bbroswerPhotos insertObject:photo atIndex:0];
    [mediaModel release];
    
}

#pragma mark - 跳转到放大查看的界面
- (void)passToFGallerViewwithIndexPath:(NSIndexPath *)indexPath andIndex:(NSInteger)index
{
    NSInteger currentIndex = 0;
    for (int presection  = 0; presection < indexPath.section; presection ++)
    {
        NSArray * dateList = [[_photoList objectAtIndex:presection] objectForKey:@"photolist"];
        currentIndex += dateList.count;
    }
    currentIndex += (indexPath.row * 4 + index);
    PhotoandVideoViewController *browser = [[PhotoandVideoViewController alloc] initWithDelegate:self];
    browser.album_Model = _albumModel;
    __block NSMutableArray * bbroswerPhotos = broswerPhotos;
    __block PhotoandVideoViewController * bbrowser = browser;
    __block NSMutableArray * bnetworkArr = networkMediaObjects;
    __block NSMutableArray * bphotoList = _photoList;
    __block UITableView * bphototableV = _phototableV;
    __block BanBu_AlbumModel * balbum_model = _albumModel;
    
    //删除相册中的照片的回调
    [browser setDeleteCallBack:^(NSInteger currentIndex,NSDictionary * resDic)
     {
         //删除照片，回调，重新请求数据，以防删除的照片是封面
         if (_refreshDataCallBack)
         {
             _refreshDataCallBack();
         }
         balbum_model.numCount -- ;
         //查找删除的文件的具体位置，在哪个数组第几个
         NSInteger numberPhoto = 0;
         for (NSMutableDictionary * dateDic in bphotoList)
         {
             NSMutableArray * dateArr = [dateDic valueForKey:@"photolist"];
             NSInteger bNum = numberPhoto + dateArr.count;
             if (bNum > currentIndex)
             {
                 [dateArr removeObjectAtIndex:(currentIndex - numberPhoto)];
                 if (dateArr.count == 0)
                 {
                     [bphotoList removeObject:dateDic];
                 }
                 
                 [bphototableV reloadData];
                 break;
             }
             else
             {
                 numberPhoto = bNum;
             }
         }
         
         [bnetworkArr removeObjectAtIndex:currentIndex];
         [bbroswerPhotos removeObjectAtIndex:currentIndex];
         if (bbroswerPhotos.count == 0)
         {
             [bbrowser dismissViewControllerAnimated:YES];
         }
         else
         {
             [bbrowser reloadData];
         }
     }];
    [browser setInitialPageIndex:currentIndex];
    BanBu_MWNavigationController *nc = [[BanBu_MWNavigationController alloc] initWithRootViewController:browser];
    [self presentViewController:nc animated:YES];
    //    [self presentModalViewController:nc animated:YES];
    
    [nc release];
   	[browser release];
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return broswerPhotos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < broswerPhotos.count)
    {
        return [broswerPhotos objectAtIndex:index];
    }
    return nil;
}

- (BanBu_MediaModel *)typeOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    return [networkMediaObjects objectAtIndex:index];
}

#pragma mark - 处于编辑状态时选中或取消选中图片
- (void)editTheSelectPhotoWithArray:(NSArray *)array andIndex:(NSInteger)index andCell:(BanBu_PhotoShowCell *)cell
{
    BanBu_MediaModel * selectmediaModel = [array objectAtIndex:index];
    //视频不可选
    if ([selectmediaModel.media_type isEqualToString:@"v"])
    {
        //视频不可以转移，设头像封面等操作
        return;
    }
    //判断是否存在，存在就取消，不存在表示选中
    BOOL isExit = NO;
    //判断是选择还是取消选择
    for (BanBu_MediaModel * mediaModel in _managePhotoArr)
    {
        if ([mediaModel.photo_id isEqualToString:selectmediaModel.photo_id])
        {
            isExit = YES;
            [_managePhotoArr removeObject:mediaModel];
            UIImageView * imageV = (UIImageView *)[cell.contentView viewWithTag:100 + index];
            UIImageView * shadeImgV = (UIImageView *)[imageV viewWithTag:200];
            [shadeImgV setHidden:YES];
            break;
        }
    }
    //没有选择过，改变为选择状态
    if (!isExit)
    {
        //记录选中照片的id
        [_managePhotoArr addObject:selectmediaModel];
        //照片没有经过选择，也可以选择,设封面和头像的时候返回设置失败
        UIImageView * imageV = (UIImageView *)[cell.contentView viewWithTag:100 + index];
        UIImageView * shadeImgV = (UIImageView *)[imageV viewWithTag:200];
        [shadeImgV setHidden:NO];
    }
    
    if (_managePhotoArr.count > 0)
    {
        //先根据数量判断
        if (_managePhotoArr.count == 1)
        {
            _setHeadBu.userInteractionEnabled = YES;
            [_setHeadBu setSelected:YES];
            //如果是私密相册或者问题相册，不能设置封面
            if (([_albumModel.album_id isEqualToString:@"__album_privacy__"]) || (_albumModel.personalbum_type == CREATE_PRIVATE) || (_albumModel.personalbum_type == CREATE_QUESSTION))
            {
                _setCoverBu.userInteractionEnabled = NO;
                [_setCoverBu setSelected:NO];
            }
            else
            {
                _setCoverBu.userInteractionEnabled = YES;
                [_setCoverBu setSelected:YES];
            }
        }
        //1-3张照片可以设为封面
        else if (_managePhotoArr.count <= 3)
        {
            _setHeadBu.userInteractionEnabled = NO;
            [_setHeadBu setSelected:NO];
            if (([_albumModel.album_id isEqualToString:@"__album_privacy__"]) || (_albumModel.personalbum_type == CREATE_PRIVATE) || (_albumModel.personalbum_type == CREATE_QUESSTION))
            {
                _setCoverBu.userInteractionEnabled = NO;
                [_setCoverBu setSelected:NO];
            }
            else
            {
                _setCoverBu.userInteractionEnabled = YES;
                [_setCoverBu setSelected:YES];
            }
            
        }
        else
        {
            _setHeadBu.userInteractionEnabled = NO;
            [_setHeadBu setSelected:NO];
            _setCoverBu.userInteractionEnabled = NO;
            [_setCoverBu setSelected:NO];
        }
        _photoMoveBu.userInteractionEnabled = YES;
        [_photoMoveBu setSelected:YES];
        
        //根据审核是否通过判断
        for (BanBu_MediaModel * mediaModel in _managePhotoArr)
        {
            if (!mediaModel.audit)
            {
                _setHeadBu.userInteractionEnabled = NO;
                [_setHeadBu setSelected:NO];
                _setCoverBu.userInteractionEnabled = NO;
                [_setCoverBu setSelected:NO];
                break;
            }
        }
    }
    else
    {
        _photoMoveBu.userInteractionEnabled = NO;
        [_photoMoveBu setSelected:NO];
        _setHeadBu.userInteractionEnabled = NO;
        [_setHeadBu setSelected:NO];
        _setCoverBu.userInteractionEnabled = NO;
        [_setCoverBu setSelected:NO];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _photoList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * dateList = [[_photoList objectAtIndex:section] objectForKey:@"photolist"];
    NSInteger addNum = 0;
    if (dateList.count % 4 > 0)
    {
        addNum = 1;
    }
    NSLog(@"第%d个数组数量:%d",section,dateList.count / 4 + addNum);
    
    return dateList.count / 4 + addNum;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentify = @"BanBu_PhotoShowCell";
    BanBu_PhotoShowCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell)
    {
        cell = [[[BanBu_PhotoShowCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify] autorelease];
    }
    NSArray * dateList = [[_photoList objectAtIndex:indexPath.section] objectForKey:@"photolist"];
    //剩余未排版照片数量
    NSInteger end = dateList.count - indexPath.row * 4;
    end = (end >= 4)?4:end;
    NSLog(@"%d",end);
    NSMutableArray * array = [[[NSMutableArray alloc]initWithCapacity:4]autorelease];
    for (int i = 0; i < end; i++)
    {
        BanBu_MediaModel * mediaModel = [dateList objectAtIndex:i + indexPath.row * 4];
        [array addObject:mediaModel];
    }
    NSLog(@"当前Row = %d:%@",indexPath.row,array);
    //自己的相册显示已设为封面,看其他人的相册不显示
    if ([_albumModel.user_id isEqualToString:MyAppDataManager.useruid])
    {
        [cell updatePhotoShowCell:array withSelectedArr:_managePhotoArr withCoverPath:_albumModel.faceIdStr andEdit:![_quitBu isHidden]];
    }
    else
    {
        [cell updatePhotoShowCell:array withSelectedArr:_managePhotoArr withCoverPath:@"" andEdit:![_quitBu isHidden]];
    }
    __block id bself = self;
    //不适用_isEditing是因为bisEditing不会随着_isåEditing改变，直接使用_isEditing会造成引用计数增加,dealloc不执行
    //    __block BOOL bisEditing = _isEditing;
    __block UIButton * bQuitBu = _quitBu;
    [cell setPhotoPressedCallBack:^(NSInteger index, NSArray * array)
     {
         NSLog(@"点击了第%d个分组第%d行第%d个",indexPath.section,indexPath.row,index);
         if (([bQuitBu isHidden]) || (!bQuitBu))
         {
             NSLog(@"跳转到放大查看的界面");
             [bself passToFGallerViewwithIndexPath:indexPath andIndex:index];
         }
         else
         {
             NSLog(@"选中图片");
             [bself editTheSelectPhotoWithArray:array andIndex:index andCell:cell];
         }
     }];
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 38;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headerV = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width, 40)]autorelease];
    headerV.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    UILabel * DateLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 13, 100, 13)];
    NSString * dateStr = [[_photoList objectAtIndex:section] objectForKey:@"date"];
    DateLabel.text = dateStr;
    DateLabel.backgroundColor = UIColorWithRGB(237, 239, 241, 1.0);
    DateLabel.font = [UIFont boldSystemFontOfSize:13.0];
    DateLabel.textColor = UIColorWithRGB(95, 93, 93, 1.0);
    [headerV addSubview:DateLabel];
    [DateLabel release];
    //添加相册属性
    if (section == 0)
    {
        
        UILabel * propertyLa = [[UILabel alloc]initWithFrame:CGRectMake(110, 12, 200, 15)];
        propertyLa.backgroundColor = [UIColor clearColor];
        propertyLa.font = [UIFont boldSystemFontOfSize:13.0];
        propertyLa.textColor = UIColorWithRGB(95, 93, 93, 1.0);
        propertyLa.textAlignment = kTextAlignmentRight;
        [headerV addSubview:propertyLa];
        if (_albumModel.album_type == ALBUM_SYSTEM)
        {
            propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_system", nil)];
//            propertyLa.text = [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_system", nil)];
        }
        else
        {
            switch (_albumModel.personalbum_type) {
                case CREATE_PUBLIC:
                {
//                    propertyLa.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_public", nil)];
                    propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_public", nil)];
                    break;
                }
                case CREATE_PRIVATE:
                {
//                    propertyLa.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_privacy", nil)];
                    propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_privacy", nil)];
                    break;
                }
                    
                case CREATE_QUESSTION:
                {
//                    propertyLa.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_encryption", nil)];
                    propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_encryption", nil)];
                    break;
                }
                    
                case CREATE_OPENGROUP:
                {
//                    propertyLa.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_designess", nil)];
                    propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_designess", nil)];
                    break;
                }
                    
                default:
                {
//                    propertyLa.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"album_property", nil),NSLocalizedString(@"property_notdesigness", nil)];
                    propertyLa.text = [NSString stringWithFormat:@"%@",NSLocalizedString(@"property_notdesigness", nil)];
                    break;
                }
            }
        }
        
        [propertyLa release];
        
    }
    return headerV;
}


#pragma mark - 相册加载更多

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ((_phototableV.contentOffset.y + _phototableV.frame.size.height - _phototableV.contentSize.height > 30)&&(_phototableV.contentSize.height > __MainScreen_Height)) {
        [self photosClickMore];
        
    }
    
}

- (void)photosClickMore
{
    //当前没有正在加载，并且存在更多数据
    
    if ((!_isLoading) && _hasMore)
    {
        
        [_moreBu setTitle:NSLocalizedString(@"loadingNotice", nil) forState:UIControlStateNormal];
        [loadingView startAnimating];
        [self getPhotosOfAlbumWithPage:_page];
        _isLoading=YES;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化点击编辑按钮出现的相册照片管理view
- (void)initManageView
{
    _manageView = [[UIView alloc]initWithFrame:CGRectMake(0, __MainScreen_Height, __MainScreen_Width, 51.5)];
    //    _manageView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_manageView];
    
    //设为头像按钮
    _setHeadBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_setHeadBu setTitle:NSLocalizedString(@"setHeadImage", nil) forState:UIControlStateNormal];
    _setHeadBu.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
    [_setHeadBu setFrame:CGRectMake(122, 10, 81.5, 31.5)];
    _setHeadBu.userInteractionEnabled = NO;
    [_setHeadBu setBackgroundImage:[UIImage imageNamed:@"manage_selected.png"] forState:UIControlStateSelected];
    [_setHeadBu setBackgroundImage:[UIImage imageNamed:@"manage_unselected.png"] forState:UIControlStateNormal];
    [_manageView addSubview:_setHeadBu];
    [_setHeadBu addTarget:self action:@selector(setUserFace) forControlEvents:UIControlEventTouchUpInside];
    
    //设为封面照按钮
    _setCoverBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_setCoverBu setTitle:NSLocalizedString(@"setAlbumCover", nil) forState:UIControlStateNormal];
    _setCoverBu.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
    [_setCoverBu addTarget:self action:@selector(setCoverAndQuitEditing) forControlEvents:UIControlEventTouchUpInside];
    [_setCoverBu setFrame:CGRectMake(220, 10, 81.5, 31.5)];
    _setCoverBu.userInteractionEnabled = NO;
    [_setCoverBu setBackgroundImage:[UIImage imageNamed:@"manage_selected.png"] forState:UIControlStateSelected];
    [_setCoverBu setBackgroundImage:[UIImage imageNamed:@"manage_unselected.png"] forState:UIControlStateNormal];
    [_manageView addSubview:_setCoverBu];
    
    //转移按钮
    
    _photoMoveBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_photoMoveBu setTitle:NSLocalizedString(@"MovePhotos", nil) forState:UIControlStateNormal];
    _photoMoveBu.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
    [_photoMoveBu addTarget:self action:@selector(movePhotosBetweenTwoAlbum) forControlEvents:UIControlEventTouchUpInside];
    [_photoMoveBu setFrame:CGRectMake(22, 10, 81.5, 31.5)];
    _photoMoveBu.userInteractionEnabled = NO;
    [_photoMoveBu setBackgroundImage:[UIImage imageNamed:@"manage_selected.png"] forState:UIControlStateSelected];
    [_photoMoveBu setBackgroundImage:[UIImage imageNamed:@"manage_unselected.png"] forState:UIControlStateNormal];
    [_manageView addSubview:_photoMoveBu];
}

#pragma mark - 调用设封面方法并退出编辑
- (void)setCoverAndQuitEditing
{
    [self setAlbumCover];
    [self quitEditState];
}

#pragma mark - 设为封面照片
- (void)setAlbumCover
{
    NSMutableString * idlistStr = [[[NSMutableString alloc]init]autorelease];
    NSMutableString * urllistStr = [[[NSMutableString alloc]init]autorelease];
    //    NSMutableString * setcoverList = [[[NSMutableString alloc]init]autorelease];
    for (BanBu_MediaModel * setcoverModel in _managePhotoArr)
    {
        //如果设封面的照片中含有未经过审核的图片，提示网络连接失败，不走接口
        if (!setcoverModel.audit)
        {
            [_managePhotoArr removeAllObjects];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"network_unavailabel", nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
            [alertView show];
            [alertView release];
            return;
        }
        [idlistStr appendFormat:@"%@,",setcoverModel.photo_id];
        [urllistStr appendFormat:@"%@,",setcoverModel.full_url];
    }
    _albumModel.faceIdStr = idlistStr;
    //要设为封面照片的缩略图路径
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",idlistStr,@"photoidlist",urllistStr,@"photourllist",nil];
    NSLog(@"要设为封面照片的相关信息:%@",parDic);
    [AppComManager getBanBuAlbumData:BanBu_v2_Set_AlbumFace par:parDic delegate:self];
    
}
#pragma mark - 设为头像
-(void)setUserFace
{
    BanBu_MediaModel * setfaceModel = [_managePhotoArr objectAtIndex:0];
    //如果设头像的照片未经过审核，提示网络连接失败，不走接口
    if (!setfaceModel.audit)
    {
        [_managePhotoArr removeAllObjects];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"network_unavailabel", nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
        [alertView show];
        [alertView release];
        [self quitEditState];
        [_managePhotoArr removeAllObjects];
        return;
    }

    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",setfaceModel.thumb_url,@"facefile",setfaceModel.full_url,@"facefull",nil];
    NSLog(@"要设为头像的相关信息:%@",parDic);
    [AppComManager getBanBuData:BanBu_v2_Set_UserFace par:parDic delegate:self];
}
#pragma mark - 转移相册中的照片
- (void)movePhotosBetweenTwoAlbum
{
    _selectTag = ACTION_MOVE;
    BanBu_PhotoMoveListViewController * movePhoto = [[BanBu_PhotoMoveListViewController alloc]init];
    __block id bself = self;
    [movePhoto setSelectAlnumCallBack:^(NSString * endAlbum_id, NSString * endAlbum_name)
     {
         [bself passTheALbumIdOfMove:endAlbum_id];
     }];
    [self.navigationController pushViewController:movePhoto animated:YES];
    [movePhoto release];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == ALERT_DELETEALBUM)
    {
        if (buttonIndex == 1)
        {
            //删除相册
            NSLog(@"删除相册");
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
            NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",nil];
            NSLog(@"要删除的相册的相关信息:%@",parDic);
            [AppComManager getBanBuData:BanBu_v2_Delete_Album par:parDic delegate:self];
        }
    }
    //    if (alertView.tag == ALERT_DELETEPHOTOS)
    //    {
    //        //确认删除照片
    //        if (buttonIndex == 1)
    //        {
    //            NSMutableString * deleteList = [[[NSMutableString alloc]init]autorelease];
    //            for (BanBu_MediaModel * selectphotoModel in _managePhotoArr)
    //            {
    //                NSString * photoid = selectphotoModel.photo_id;
    //                [deleteList appendFormat:@"%@,",photoid];
    //            }
    //            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
    //            NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"albumid",deleteList,@"photoidlist",nil];
    //            NSLog(@"要删除的照片的相关信息:%@",parDic);
    //            [AppComManager getBanBuData:BanBu_v2_Delete_Fileof_Albumid par:parDic delegate:self];
    //        }
    //    }
    //
}
#pragma mark - 转移/复制照片操作

- (void)passTheALbumIdOfMove:(NSString *)album_id
{
    NSMutableString * deleteList = [[[NSMutableString alloc]init]autorelease];
    for (BanBu_MediaModel * selectphotoModel in _managePhotoArr)
    {
        NSString * photoid = selectphotoModel.photo_id;
        [deleteList appendFormat:@"%@,",photoid];
    }
    if (_selectTag == ACTION_MOVE)
    {
        NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"fromalbumid",deleteList,@"photoidlist",album_id,@"toalbumid",@"move",@"actionof",nil];
        NSLog(@"要转移的照片的相关信息:%@",parDic);
        [AppComManager getBanBuData:BanBu_v2_Move_Fileof_Albumid par:parDic delegate:self];
        return;
    }
    else if (_selectTag == ACTION_COPY)
    {
        NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_albumModel.album_id,@"fromalbumid",deleteList,@"photoidlist",album_id,@"toalbumid",@"copy",@"actionof",nil];
        NSLog(@"要复制的照片的相关信息:%@",parDic);
        [AppComManager getBanBuData:BanBu_v2_Move_Fileof_Albumid par:parDic delegate:self];
        return;
    }
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
